package com.example.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.component.EoSynchroniseTask;
import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import com.example.demo.service.EoService;
import com.example.demo.utils.JDBCUtil;
import com.example.demo.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Service
public class EoServiceImpl extends ServiceImpl<EoMapper, EO> implements EoService {
    @Autowired
    EoMapper eoMapper;
    @Autowired
    ExecuteLeaderMapper executeLeaderMapper;
    @Autowired
    ExecuteDeptMapper executeDeptMapper;
    @Autowired
    ExecutePeopleMapper executePeopleMapper;
    @Autowired
    DeptMapper deptMapper;
    @Autowired
    ExecuteTimetableMapper timetableMapper;
    @Autowired
    ActivityMapper activityMapper;

    @Override
    public Result<?> add(EO eo, HttpServletRequest request){
        SysUser sysUser = TokenUtils.getUserInfo(request);
        if (sysUser == null)
            return Result.error("500", "未获取到user信息");

        if(eo.getTitle() == null || eo.getTitle().length() == 0){
            return Result.error("401", "请输入EO单标题");
        }else if(eo.getName() == null || eo.getName().length() == 0){
            return Result.error("401", "请输入活动名称");
        }

        java.util.Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        eo.setCreateTime(sdf.format(day));
        eo.setCreateUser(sysUser.getPeopleName());

        if(eo.getStartTime() != null && eo.getEndTime() != null){
            long d = EoSynchroniseTask.getPeriod(eo.getStartTime(), eo.getEndTime());
            eo.setPeriod(d);
        }
        if (eo.getIsColloquiumNeeded() == null){
            eo.setIsColloquiumNeeded(false);
        }
        eo.setStatus("编辑中");
        eo.setIsActive(true);
        eo.setOrigin("EO单系统新增");

        eoMapper.insert(eo);

        addLists(eo.getId(), eo.getLeaders(), eo.getTimetables(), eo.getDeps(), eo.getStaffs());
        return Result.success(eo.getId());
    }

    @Override
    public Result<?> update(EO eo, HttpServletRequest request){
        SysUser sysUser = TokenUtils.getUserInfo(request);
        if (sysUser == null)
            return Result.error("500", "未获取到user信息");

        if(eo.getTitle() == null || eo.getTitle().length() == 0){
            return Result.error("401", "请输入EO单标题");
        }else if(eo.getName() == null || eo.getName().length() == 0){
            return Result.error("401", "请输入活动名称");
        }

        if(eoMapper.selectById(eo.getId()) == null){
            return Result.error("400", "找不到记录");
        }

        java.util.Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        eo.setModifyTime(sdf.format(day));
        eo.setModifyUser(sysUser.getPeopleName());

        if(eo.getStartTime() != null && eo.getEndTime() != null){
            long d = EoSynchroniseTask.getPeriod(eo.getStartTime(), eo.getEndTime());
            eo.setPeriod(d);
        }
        if (eo.getIsColloquiumNeeded() == null){
            eo.setIsColloquiumNeeded(false);
        }

        addLists(eo.getId(), eo.getLeaders(), eo.getTimetables(), eo.getDeps(), eo.getStaffs());

        eo.setIsActive(true);
        eoMapper.updateById(eo);
        return Result.success();
    }

    @Override
    public Result<?> synchronise(HttpServletRequest request) throws Exception {
        JDBCUtil.getConnection();
        java.util.Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        LambdaQueryWrapper<BdActivity> wrapper = Wrappers.lambdaQuery();
        wrapper.isNotNull(BdActivity::getQuatationId);
        List<BdActivity> activities = activityMapper.selectList(wrapper);

        SysUser sysUser = TokenUtils.getUserInfo(request);
        if (sysUser == null)
            return Result.error("500", "未获取到user信息");

        for(BdActivity item : activities){

            EO eo1 = eoMapper.selectByQuatationId(item.getQuatationId());
            if (eo1 == null) {
                EO eo = new EO();
                eo.setQuatationId(item.getQuatationId());
                eo.setTitle(item.getName());
                eo.setName(item.getName());
                eo.setStartTime(item.getStartDate());
                eo.setEndTime(item.getEndDate());
                eo.setPeriod(EoSynchroniseTask.getPeriod(item.getStartDate(), item.getEndDate()));
                eo.setGuestName(item.getGuestName());
                eo.setGuestNum(item.getGuestCount());
                eo.setIsActive(item.getIsActive());
                eo.setCreateTime(sdf.format(day));
                eo.setCreateUser(sysUser.getPeopleName());
                eo.setLocation(item.getVenue());
                eo.setStatus("未编辑");
                eo.setOrigin("场馆运营系统同步");
                eo.setType("活动");
                eoMapper.insert(eo);
            }
        }
//        List<EO> eos = eoMapper.selectList(null);
//        for(EO item : eos){
//            if(item.getType().equals("活动")){
//                item.setType("1");
//                eoMapper.updateById(item);
//            }else{
//                item.setType("2");
//            }
//        }
        return Result.success();
    }

    @Override
    public Result<?> delete(Long id){
        EO eo = eoMapper.selectById(id);
        java.util.Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if(eo != null){
            eo.setIsActive(false);
            eo.setModifyUser("管理员");
            eo.setModifyTime(sdf.format(day));
            eoMapper.updateById(eo);
        } else {
            return Result.error("400", "找不到记录");
        }
        return Result.success();
    }

    @Override
    public Result<?> list(Integer pageNum,
                          Integer pageSize,
                          String search,
                          String month,
                          String departmentId,
                          Integer peopleId,
                          String status,
                          String origin,
                          String type) {
        if(peopleId != 0) {
            List<EO> list  = eoMapper.pagePeople(peopleId, type);
            Page<EO> page = new Page<>();
            page.setTotal(list.size());
            page.setRecords(list);
            page.setCurrent(pageNum);
            page.setSize(pageSize);
            return Result.success(page);
        } else if (StrUtil.isNotEmpty(departmentId)) {
            List<EO> list = eoMapper.pageDept(departmentId, type);
            Page<EO> page = new Page<>();
            page.setTotal(list.size());
            page.setRecords(list);
            page.setCurrent(pageNum);
            page.setSize(pageSize);
            return Result.success(page);
        } else {
            LambdaQueryWrapper<EO> wrapper = Wrappers.lambdaQuery();
            if (StrUtil.isNotBlank(type)) {
                wrapper.eq(EO::getType, type);
            }
            if (StrUtil.isNotBlank(search)) {
                wrapper.like(EO::getName, search);
            }
            if (StrUtil.isNotBlank(month)) {
                wrapper.like(EO::getStartTime, month);
            }
            if (StrUtil.isNotBlank(status)) {
                wrapper.like(EO::getStatus, status);
            }
            if (StrUtil.isNotBlank(origin)) {
                wrapper.like(EO::getOrigin, origin);
            }
            wrapper.eq(EO::getIsActive, true);
            wrapper.orderByDesc(EO::getStartTime);
            wrapper.orderByDesc(EO::getModifyTime);

            Page<EO> eoPage = eoMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
            updateStatus();
            return Result.success(eoPage);
        }
    }

    @Override
    public Map<String, Object> getMap(Long id){
        Map<String, Object> map = new HashMap<>();
        EO eo = eoMapper.selectById(id);
        String[] str = {"（一）", "（二）", "（三）", "（四）", "（五）", "（六）", "（七）", "（八）", "（九）", "（十）"};
        LambdaQueryWrapper<EoExecuteTimetable> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(EoExecuteTimetable::getEoId, id);
        List<EoExecuteTimetable> timetables = timetableMapper.selectList(wrapper1);
        LambdaQueryWrapper<EoExecutePeople> wrapper2 = Wrappers.lambdaQuery();
        wrapper2.eq(EoExecutePeople::getEoId, id);
        List<EoExecutePeople> people = executePeopleMapper.selectList(wrapper2);
        LambdaQueryWrapper<EoExecuteDept> wrapper3 = Wrappers.lambdaQuery();
        wrapper3.eq(EoExecuteDept::getEoId, id);
        List<EoExecuteDept> departments = executeDeptMapper.selectList(wrapper3);
        LambdaQueryWrapper<EoExecuteLeader> wrapper4 = Wrappers.lambdaQuery();
        wrapper4.eq(EoExecuteLeader::getEoId, id);
        List<EoExecuteLeader> leaders = executeLeaderMapper.selectList(wrapper4);
        List<Map<String,Object>> timeList = new ArrayList<>();
        List<Map<String,Object>> peopleList = new ArrayList<>();
        List<Map<String,Object>> deptList = new ArrayList<>();
        List<Map<String,Object>> leaderList = new ArrayList<>();

        for (int n = 0; n < timetables.size(); n++) {
            Map<String,Object> timetableMap = new HashMap<>();
            timetableMap.put("start_time", timetables.get(n).getStartTime());
            timetableMap.put("end_time", timetables.get(n).getEndTime());
            timetableMap.put("venue", timetables.get(n).getVenue());
            timetableMap.put("project", timetables.get(n).getProject());
            timeList.add(timetableMap);
        }
        for (int m = 0; m < people.size(); m++){
            Map<String,Object> peopleMap = new HashMap<>();
            peopleMap.put("index", m+1);
            peopleMap.put("name", people.get(m).getName());
            peopleMap.put("phone", people.get(m).getPhone());
            peopleMap.put("department", people.get(m).getDeptName());
            peopleMap.put("duty", people.get(m).getDescription());
            peopleMap.put("location", people.get(m).getLocation());
            peopleList.add(peopleMap);
        }
        for (int l = 0; l < departments.size(); l++){
            Map<String,Object> deptMap = new HashMap<>();
            deptMap.put("index", str[l]);
            deptMap.put("deptName", departments.get(l).getDeptName());
            deptMap.put("content", departments.get(l).getDescription());
            deptList.add(deptMap);
        }
        for (int q = 0; q < leaders.size(); q++){
            Map<String,Object> leaderMap = new HashMap<>();
            leaderMap.put("index", q+1);
            leaderMap.put("name", leaders.get(q).getName());
            leaderMap.put("company", leaders.get(q).getCompany());
            leaderMap.put("class_rank", leaders.get(q).getCompany());
            leaderMap.put("comment", leaders.get(q).getCompany());
            leaderList.add(leaderMap);
        }
        Map<String, Object> nullMap = new HashMap<>();
        nullMap.put("index", "/");
        nullMap.put("name", "/");
        nullMap.put("company", "/");
        nullMap.put("class_rank", "/");
        nullMap.put("comment", "/");
        if (leaderList.size() == 0) leaderList.add(nullMap);
        String colloquium;
        if(eo.getIsColloquiumNeeded() == null || !eo.getIsColloquiumNeeded()){
            colloquium = "/";
        }else {
            if (eo.getColloquiumStart() == null) eo.setColloquiumStart("/");
            if (eo.getColloquiumEnd() == null) eo.setColloquiumEnd("/");
            else eo.setColloquiumEnd(eo.getColloquiumEnd().substring(11, 16));
            if (eo.getColloquiumVenue() == null) eo.setColloquiumVenue("/");
            if (eo.getColloquiumCount() == null) eo.setColloquiumCount("/");
            colloquium = eo.getColloquiumStart() + "-" + eo.getColloquiumEnd() + "—" + eo.getColloquiumVenue() + " " + eo.getColloquiumCount() + "人";
        }
        String vehicles = eo.getVisitVehicles();
        if(eo.getVisitVehicles() == null){
            vehicles = "/";
        }

        try{

            SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String outTime = s2.format(s2.parse(eo.getModifyTime()));

            map.put("title", eo.getTitle());
            map.put("modifyTime", outTime);
            map.put("startTime", eo.getStartTime());
            if(!eo.getEndTime().isEmpty()) map.put("endTime", eo.getEndTime().substring(11, 16));
            map.put("number", eo.getGuestNum());
            map.put("colloquium", colloquium);
            map.put("route", eo.getRouteText());
            map.put("visit_vehicles", vehicles);
            map.put("peopleList", peopleList);
            map.put("deptList", deptList);
            map.put("guestName", eo.getGuestName());
            map.put("schedule", eo.getSchedule());
            if (StrUtil.isEmpty(eo.getGuestCommit())) map.put("guest_commit", "<p>/</p>");
            else map.put("guest_commit", eo.getGuestCommit());
            map.put("time_text", eo.getTimeText());
            map.put("leaderList", leaderList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    public void addLists(Integer id,
                         ArrayList<EoExecuteLeader> leaders,
                         ArrayList<EoExecuteTimetable> timetables,
                         ArrayList<EoExecuteDept> dept,
                         ArrayList<EoExecutePeople> people){
        if (leaders != null) {
            for(EoExecuteLeader item : leaders){
                if(item.getId() == null){
                    item.setEoId(id);
                    executeLeaderMapper.insert(item);
                }else{
                    executeLeaderMapper.updateById(item);
                }
            }
        }
        if(timetables != null){
            for(EoExecuteTimetable item : timetables){
                if(item.getId() == null){
                    item.setEoId(id);
                    timetableMapper.insert(item);
                }else{
                    timetableMapper.updateById(item);
                }
            }
        }
        if(dept != null){
            for(EoExecuteDept item : dept){
                if(item.getId() == null){
                    item.setEoId(id);
                    executeDeptMapper.insert(item);
                }else{
                    executeDeptMapper.updateById(item);
                }
            }
        }
        if(people != null){
            for(EoExecutePeople item : people){
                if(item.getId() == null){
                    item.setEoId(id);
                    executePeopleMapper.insert(item);
                }else{
                    executePeopleMapper.updateById(item);
                }
            }
        }
    }

    public void updateStatus() {
        java.util.Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String now = sdf.format(day);

        List<EO> eos = eoMapper.selectList(null);
        for(EO item : eos){
            try{
                if((!item.getStartTime().isEmpty()) && (!item.getEndTime().isEmpty())){
                    Date start = sdf.parse(item.getStartTime());
                    Date end = sdf.parse(item.getEndTime());
                    Date nowTime = sdf.parse(now);
                    if(nowTime.after(start) && nowTime.before(end)){
                        item.setStatus("执行中");
                    }else if(nowTime.after(end)){
                        item.setStatus("已完成");
                    }
                }

            }catch (Exception e){
                e.printStackTrace();
            }
            eoMapper.updateById(item);
        }
    }

//    public Long getPeriod(String start, String end){
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        long d = 0L;
//        try{
//            long d1 = format.parse(start).getTime();
//            long d2 = format.parse(end).getTime();
//            d = (d2 - d1)/(1000 * 60 * 60 * 24);
//        }catch (ParseException e){
//            e.printStackTrace();
//        }
//        return d+1;
//    }

}
